package com.aeasycredit.credit.tuef.manager;

import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import com.aeasycredit.credit.tuef.handler.TuefDataHandler;

@Component
public class TuefDataHandlerFactory {
    
    @Autowired
    private ApplicationContext applicationContext;
    
    private Map<Class, TuefDataHandler> handlerMap = null;
    
    @PostConstruct
    public void init() {
        Collection<TuefDataHandler> handlerList = applicationContext.getBeansOfType(TuefDataHandler.class).values();
        handlerMap = handlerList.stream().collect(Collectors.toMap(TuefDataHandler::supportTuefSegment, Function.identity(), 
                (u,v) -> { throw new IllegalStateException(String.format("Duplicate key %s", u)); },
                () ->  new LinkedHashMap<Class, TuefDataHandler>()));
    }
    
    public TuefDataHandler create(Class clazz) {
        return handlerMap.get(clazz);
    }
    
}
